package com.ynny.chapter09.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/files")
public class UploadController {

    @Value("D:/upload/")
    String savePath;

    //form表单形式上传文件
    @PostMapping("/upload01")
    public String upload01(@RequestParam(name = "pic")
                               MultipartFile pic) throws IOException {
        System.out.println("文件名称为: " + pic.getOriginalFilename());
        System.out.println("文件大小: " + pic.getSize());
        //文件上传的步骤
        //1.上传的目录 位置  D:/upload/
        //判断这个文件夹是否存在
        File path = new File(savePath);
        if (!path.exists()){
            path.mkdirs();
        }
        //2.获取文件信息  //D:/upload/login.png
        String originalFilename = pic.getOriginalFilename();
        //随机字符串 保存一个新的文件
        UUID uuid = UUID.randomUUID();
        File file = new File(savePath + uuid + originalFilename);
        //3.保存文件
        pic.transferTo(file);
        return "/upload/" + uuid + originalFilename;
    }




}
